<template>
  <div class="spec">
    <el-form>
      <el-button class="btn" type="primary" @click="addSpec"> 添加规格</el-button>
      <el-text class="spec-checkbox" v-for="item in data.goodsAttr" :key="item.id">
        <template #default>
          <span class="text" style="margin-bottom: 15px;">{{ item.name }}</span>
          <el-icon class="delete" @click="deleteSpec(item)">
            <Delete />
          </el-icon>
          <div class="spec-value">
            <div v-for="vo in item.specValues" :key="vo.id || 'empty-' + index">
              <el-checkbox class="value-checkbox" @change="specChange(item,vo)" :value="vo.check||false"
                           :checked="vo.check||false">{{ vo.name }}
              </el-checkbox>
              <el-icon v-if="!vo.check" class="delete" @click="deleteValue(vo, index)">
                <Delete />
              </el-icon>
            </div>
            <el-button type="primary" class="value-btn" link icon="Plus" @click="addSpecValue(item)">新增规格项
            </el-button>
          </div>
        </template>
      </el-text>
    </el-form>

  </div>
  <!--sku-->
  <div class="sku">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="SKU信息" prop="goodsSkus">
          <el-table :data="data.skus" border>
            <el-table-column v-slot="scope" label="规格名称" width="200">
              <input v-model="scope.row.skuName" class="custom-input" />

            </el-table-column>
            <el-table-column label="图片" v-slot="scope" width="60" align="center">
              <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :show-file-list="false"
                :on-success="
                    (response: any, uploadFile: any, fileList: any) =>
                      handleSkuSuccess(
                        response,
                        uploadFile,
                        fileList,
                        scope.row
                      )
                  "
                :headers="headers"
              >
                <img
                  v-if="scope.row.imgUrl"
                  :src="scope.row.imgUrl"
                  class="avatar"
                  alt=""
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-table-column>
            <el-table-column v-slot="scope" label="商品价格" width="160">
              <input v-model="scope.row.price" class="custom-input" />
            </el-table-column>
            <el-table-column v-slot="scope" label="市场价" width="160">
              <input v-model="scope.row.oldPrice" class="custom-input" />
            </el-table-column>
            <el-table-column v-slot="scope" label="库存数量" width="200">
              <input v-model="scope.row.stock" class="custom-input" />
            </el-table-column>
            <el-table-column v-slot="scope" label="商家编码">
              <input v-model="scope.row.skuCode" class="custom-input" />
            </el-table-column>
            <el-table-column v-slot="scope" label="商品条形码">
              <input v-model="scope.row.barCode" class="custom-input" />
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-col>
    </el-row>
  </div>
  <div>
    <el-form>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item class="btn-bottom">
            <el-button :icon="CircleCheck" type="success" :loading="loading" @click="handleGoods">发布</el-button>
            <el-button @click="cancel">返回</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

  </div>
  <!-- 规格名称弹窗 -->
  <el-dialog v-model="dialogVisible" title="添加规格" width="500px">
    <el-form :model="specForm">
      <el-form-item label="商品ID" label-width="80px">
        <el-input v-model="specForm.goodsId" disabled></el-input>
      </el-form-item>
      <el-form-item label="规格名称" label-width="80px">
        <el-input v-model="specForm.name" placeholder="输入规格名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">返回</el-button>
                    <el-button type="primary" @click="handleSpec">添加</el-button>
                </span>
    </template>
  </el-dialog>
  <!--规格值弹窗-->
  <el-dialog v-model="dialogValue" title="添加规格" width="500px">
    <el-form :model="specValueForm">
      <el-form-item label="规格ID" label-width="80px">
        <el-input v-model="specValueForm.specId" disabled></el-input>
      </el-form-item>
      <el-form-item label="属性名称" label-width="80px">
        <el-input v-model="specValueForm.name" placeholder="输入规格值名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogValue = false">返回</el-button>
                    <el-button type="primary" @click="handleSpecValue">添加</el-button>
                </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { addGoodsSpec, delGoodsSpec, specByGoodsIdListApi } from '@/api/mall/goodsSpec';
import { CircleCheck, Delete, Plus } from '@element-plus/icons-vue';
import { globalHeaders } from '@/utils/request';
import { addGoodsSpecVal, delGoodsSpecVal } from '@/api/mall/goodsSpecVal';
import { delGoodsSkuApi, updateMallGoods } from '@/api/mall/mallGoods';


const emit = defineEmits(['step']);
const loading = ref(false);
const props = defineProps(['goods']);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址
const headers = ref(globalHeaders());

const specForm = ref({
  name: '',
  goodsId: ''
});
const specValueForm = ref({
  name: '',
  specId: ''
});
const data = reactive({
  goodsAttr: [],
  skus: []
});
const dialogVisible = ref(false);
const dialogValue = ref(false);
//sku图片
const handleSkuSuccess = (
  response: any,
  uploadFile: any,
  fileList: any,
  row: any
) => {
  row.imgUrl = response.data.url;
};
/*获取商品规格*/
const specQueryParams = ref({
  goodsId: props.goods.id
});
/*获取规格列表*/
const getSpecs = async () => {
  const res = await specByGoodsIdListApi(specQueryParams.value);
  data.goodsAttr = res.data;
  console.log(res);
};

/*返回或取消*/
const cancel = () => {
  emit('step', 1);
};
/*添加商品规格界面*/
const addSpec = () => {
  dialogVisible.value = true;

};

/*添加商品规格操作*/
const handleSpec = async () => {
  const res = await addGoodsSpec(specForm.value);
  if (res.code === 200) {
    await getSpecs();//刷新spec列表
    dialogVisible.value = false; //关闭弹窗
    //重置输入框
    specForm.value.name = '';
  }
};
/*删除商品规格*/
const deleteSpec = async (ev) => {
  const { code } = await delGoodsSpec(ev.id);
  if (code === 200) {
    //刷新规格列表
    await getSpecs();
  }
};
/*添加商品规格值界面*/
const addSpecValue = (ev) => {
  dialogValue.value = true;
  specValueForm.value.specId = ev.id;
};
/*添加商品规格值操作*/
const handleSpecValue = async () => {
  const { code } = await addGoodsSpecVal(specValueForm.value);
  if (code === 200) {
    //重置输入框
    specValueForm.value.name = '';
    //关闭弹窗
    dialogValue.value = false;
    //刷新商品规格
    await getSpecs();
  }
};

/*删除框*/
const deleteValue = (item) => {
  //先执行后台删除
  delGoodsSpecVal(item.id)
    .then((res) => {
      //删除前端数据
      if (res.code === 200) {
        //删除对应的sku
      }
      //刷新specValue列表
      getSpecs();
    })
    .catch((error) => {
      ElMessage.error('删除失败', error);
    });
};

/*==================属性选择操作 start =========================*/
const specChange = (attrs, specs) => {
  let index = -1;
  data.goodsAttr.forEach((items, key) => {
    if (items.id === attrs.id) {
      index = key;
    }
  });

  if (index !== -1) {
    data.goodsAttr[index].specValues.forEach((item) => {
      if (item.id === specs.id) {
        item.check = item.check === undefined ? true : !item.check;
      }
    });
  }

  structureSku();
};

const structureSku = () => {
  let skuList = [];
  let attrList = [];
  let attrListName = [];
  let i = 0;

  data.goodsAttr.forEach((items) => {
    let checkedValues = [];
    items.specValues.forEach(specItem => {
      if (specItem.check) {
        checkedValues.push(specItem.id);
        if (attrList[i] === undefined) {
          attrList[i] = [];
          attrListName[i] = [];
        }
        attrList[i].push(specItem.id);
        attrListName[i].push(specItem.name);
      }
    });
    if (checkedValues.length > 0) {
      i++;
    }
  });

  if (attrList.length === 0) {
    data.skus = [];
    //如果清空，则对当前的skus进行删除
    delSkus(props.goods.id);
    return;
  }
  // 处理单选情况
  if (attrList.every(arr => arr.length === 1)) {
    // 直接为每个选中的规格值生成 SKU
    attrList.forEach((ids, index) => {
      const skuAttributes = [{
        name: data.goodsAttr[index].name,
        valueName: attrListName[index][0]
      }];

      skuList.push({
        specId: ids,
        skuName: attrListName[index][0],
        oldPrice: 0,
        price: 0,
        stock: 0,
        attributes: skuAttributes
      });
    });
  } else {
    // 处理多选情况
    const attrName = cartesianProduct(attrListName);
    const attrId = cartesianProduct(attrList);

    attrId.forEach((ids, key) => {
      let skuAttributes = [];
      for (let j = 0; j < ids.length && j < data.goodsAttr.length; j++) {
        if (attrList[j] && attrList[j].length > 0) {
          const index = attrList[j].indexOf(ids[j]);
          if (index !== -1) {
            skuAttributes.push({
              name: data.goodsAttr[j].name,
              valueName: attrListName[j][index]
            });
          }
        }
      }

      skuList.push({
        specId: ids,
        skuName: attrName[key].join('+'),
        oldPrice: 0,
        price: 0,
        stock: 0,
        attributes: skuAttributes
      });
    });
  }
  // 更新SKU列表
  if (data.skus && data.skus.length > 0) {
    const newSkuIds = skuList.map(sku => JSON.stringify(sku.specId.sort((a, b) => a - b)));
    const oldSkuIds = data.skus.map(sku => JSON.stringify(sku.specId.sort((a, b) => a - b)));

    // 移除不再存在的SKU
    data.skus = data.skus.filter((sku, index) => newSkuIds.includes(oldSkuIds[index]));

    // 添加新的SKU
    skuList.forEach(newSku => {
      if (!oldSkuIds.includes(JSON.stringify(newSku.specId.sort((a, b) => a - b)))) {
        data.skus.push(newSku);
      }
    });
  } else {
    data.skus = skuList;
  }
};

const cartesianProduct = (array) => {
  if (array.length == 1) {
    return array;
  }
  return array.reduce(function(a, b) {
    return a.map(function(x) {
      return b.map(function(y) {
        return x.concat(y);
      });
    }).reduce(function(a, b) {
      return a.concat(b);
    }, []);
  }, [[]]);
};

/*==================属性选择操作 end =========================*/

/*商品发布*/
const handleGoods = async () => {
  // 将 data.skus 中的每个对象的 specId 和 attributes 转换为 JSON 字符串
  props.goods.skus = data.skus.map((obj) => {
    // 创建一个新对象，并更新 specId 和 attributes 为 JSON 字符串
    return {
      ...obj,
      specId: JSON.stringify(obj.specId),
      attributes: JSON.stringify(obj.attributes)
    };
  });
  // 将转换后的数组赋值给 props.goods.skus
  const { code } = await updateMallGoods(props.goods);
  if (code === 200) {
    //关闭当前页
    emit('step', 2);
  }
};
const delSkus = async (goodsId) => {
  try {
    const { code } = await delGoodsSkuApi(goodsId);
    if (code === 200) {
      ElMessage.success('原有sku商品已被全部删除');
    }
  } catch (error) {
    ElMessage.error(error);
  }
};
onMounted(() => {
  getSpecs();
});
/*对外暴露*/

</script>

<style scoped lang="scss">
.spec {
  display: block;
  flex-direction: column;

  .btn {
    margin: 10px;
  }

  .spec-checkbox {
    display: block;
    flex-direction: column;
    background: #F7F8FA;
    margin-bottom: 10px;
    padding: 30px 20px;
    border-radius: 10px;

    .text {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .spec-value {
      margin-top: 10px;
      display: flex;

      .value-checkbox {
        padding-left: 20px;
      }

      .value-btn {
        margin-left: 15px;
      }
    }
  }
}

.delete {
  margin-left: 5px;
  margin-right: 20px;
  cursor: pointer;
  color: #FF6600;
}

.sku {
  margin-top: 10px;
}

.custom-input {
  width: 100%;
  height: 30px;
  border: none;

  &:focus {
    outline: none;
  }
}

.empty-placeholder {
  font-size: 12px;
  color: #c03639;
}

.avatar-uploader .avatar {
  width: 30px;
  height: 30px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 26px;
  color: #8c939d;
  width: 30px;
  height: 30px;
  text-align: center;
}

.btn-bottom {
  margin-top: 20px;
}
</style>
